package com.example.demo.service.impl;

import com.example.demo.client.vm.sysbasequery.UserGroupTreeVm;
import com.example.demo.domain.UserGroup;
import com.example.demo.enums.ResourceObjectTypeEnum;
import com.example.demo.format.TreeBuilder;
import com.example.demo.mapper.UserGroupMapper;
import com.example.demo.repository.UserGroupRepository;
import com.example.demo.security.SecurityUtils;
import com.example.demo.service.BaseService;
import com.example.demo.service.UserGroupService;
import com.example.demo.web.rest.constant.DatabaseConstant;
import com.example.demo.web.rest.evt.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 *
 * @Author zhengmf
 * @Date 2018/12/25  11:37
 */
@Service
@Transactional
public class UserGroupServiceImpl extends BaseService implements UserGroupService {
    @Autowired
    private UserGroupMapper userGroupMapper;
    @Autowired
    private UserGroupRepository userGroupRepository;

    @Override
    public Integer addGroupUserByGroupIdAndUserIds(RelationEvt evt) {
        return userGroupMapper.addGroupUserByGroupIdAndUserIds(evt);
    }

    @Override
    public Integer delGroupUserByGroupIdAndUserIds(RelationEvt evt) {
        return userGroupMapper.delGroupUserByGroupIdAndUserIds(evt);
    }

    @Override
    public void delUserGroup(IdEvt evt) {
        RelationEvt relationEvt = new RelationEvt();
        relationEvt.setId(evt.getId());
        //删除用户与用户组的关系
        Integer delCount = userGroupMapper.delGroupUserByGroupIdAndUserIds(relationEvt);
        logger.info("删除用户与用户组的关系：" + delCount);
        //删除用户组与角色的关系
        delCount = userGroupMapper.delGroupRoleByGroupIdAndRoleIds(relationEvt);
        logger.info("删除用户组与角色的关系：" + delCount);
        //删除用户组
        userGroupRepository.deleteById(evt.getId());
        //删除用户组分配的资源
        ResourceRelationEvt gr = new ResourceRelationEvt();
        gr.setId(evt.getId());
        gr.setType(ResourceObjectTypeEnum.GROUP_REF.getValue());
        userGroupMapper.delGroupResource(gr);
        logger.info("删除用户组的ID：" + evt.getId());
    }

    @Override
    public Long saveUserGroup(SaveUserGroupEvt evt) throws ParseException {
        UserGroup userGroup = new UserGroup();
        BeanUtils.copyProperties(evt.getUserGroup(),userGroup);
        String userName = SecurityUtils.getCurrentUserLogin().get();
        Date now = nowDateTime();
        if(evt.getType()==1){//新增
            userGroup.setCreateUserName(userName);
            userGroup.setInsertTime(now);
            TableIdSizeEvt tableIdSizeEvt = new TableIdSizeEvt(DatabaseConstant.TABLE_NAME_GROUP,DatabaseConstant.ID_SIZE);
            userGroup.setGroupId(baseQueryClient.getTableId(tableIdSizeEvt));
        }
        userGroup.setUpdateUserName(userName);
        userGroup.setUpdateTime(now);
        Long parentId = userGroup.getParentId();
        String parentFullGroupId = "";
        String parentGroupFullName = "";
        if(parentId != null && parentId != 0){
            IdEvt idEvt = new IdEvt();
            idEvt.setId(parentId);
            parentFullGroupId  = baseQueryClient.getFullGroupIdByGroupId(idEvt).getBody();
            parentGroupFullName = baseQueryClient.getGroupFullNameByGroupId(idEvt).getBody();
        }
        UserGroup newGroup = userGroupRepository.save(userGroup);
        Long groupId = newGroup.getGroupId();
        if(parentId == null){
            userGroupRepository.updateFullGroupId(","+groupId+",",groupId);
            userGroupRepository.updateGroupFullName(userGroup.getGroupName(),groupId);
        }else {
            userGroupRepository.updateFullGroupId(parentFullGroupId + groupId+",",groupId);
            userGroupRepository.updateGroupFullName(parentGroupFullName + "/" + userGroup.getGroupName(),groupId);
        }
        // 保存用户组和角色关系
        saveUserGroupRole(evt.getAddRoleIds(),evt.getDelRoleIds(),groupId);
        // 保存用户组和功能权限关系
        saveUserGroupPermission(evt.getAddPermissionIds(), evt.getDelPermissionIds(), groupId);
        // 保存用户组和资源关系
        saveUserGroupResource(evt.getAddResource(), evt.getDelResource(), groupId);
        return groupId;
    }

    @Override
    public List<UserGroupTreeVm> getParentGroupTree(IdEvt evt) {
        List<UserGroupTreeVm> list = TreeBuilder.newTreeBuilder(UserGroupTreeVm.class,Long.class)
                .buildToTreeList(userGroupMapper.getParentGroupTree(evt));
        Long id = evt.getId();
        deleteSelf(list,id);
        return list;
    }

    public void deleteSelf(List<UserGroupTreeVm> list,Long id){
        if(list == null || list.size()==0){
            return;
        }
        for (int i=0;i<list.size();i++) {
            UserGroupTreeVm vm = list.get(i);
            if (vm.getId().equals(id)) {
                list.remove(i);
                return;
            }
            if (vm.getChildren()!=null && vm.getChildren().size()>0) {
                deleteSelf(vm.getChildren(),id);
            }
        }
    }

    /**
     * 保存用户组与角色信息
     * @return
     */
    private void saveUserGroupRole(List<String> addRoleList, List<String> delRoleList, Long groupId) {
        Integer count;
        // 删除用户组与角色关系表
        RelationEvt relationEvt = new RelationEvt();
        relationEvt.setId(groupId);
        if(delRoleList != null && delRoleList.size()>0) {
            relationEvt.setRelateIds(delRoleList);
            count = userGroupMapper.delGroupRoleByGroupIdAndRoleIds(relationEvt);
            logger.info("删除用户组与角色关系总数：" + count);
        }
        // 添加用户组与角色关系表
        if(addRoleList != null && addRoleList.size()>0) {
            relationEvt.setRelateIds(addRoleList);
            count = userGroupMapper.addGroupRoleByGroupIdAndRoleIds(relationEvt);
            logger.info("增加用户组与角色关系总数：" + count);
        }
    }

    /**
     * 保存用户组功能权限信息
     * @return
     */
    private void saveUserGroupPermission(List<String> addPermissionList, List<String> delPermissionList, Long groupId) {
        Integer count;
        // 删除用户组与功能权限关系表
        RelationEvt relationEvt = new RelationEvt();
        relationEvt.setId(groupId);
        if(delPermissionList != null && delPermissionList.size()>0) {
            relationEvt.setRelateIds(delPermissionList);
            count = userGroupMapper.delGroupPermissionByGroupIdAndPermissionIds(relationEvt);
            logger.info("删除用户组与功能权限关系总数：" + count);
        }
        // 添加用户组与权限关系
        if(addPermissionList != null && addPermissionList.size()>0) {
            relationEvt.setRelateIds(addPermissionList);
            count = userGroupMapper.addGroupPermissionByGroupIdAndPermissionIds(relationEvt);
            logger.info("增加用户组与功能权限关系总数：" + count);
        }
    }
    /**
     * 保存用户组资源信息
     * @return
     */
    private void saveUserGroupResource(List<ResourceEvt>  addResource, List<ResourceEvt>  delResource, Long groupId){
        Integer count;

        ResourceRelationEvt resourceRelationEvt = new ResourceRelationEvt();
        resourceRelationEvt.setId(groupId);
        resourceRelationEvt.setType(ResourceObjectTypeEnum.GROUP_REF.getValue());
        String username = SecurityUtils.getCurrentUserLogin().get();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = format.format(new Date());
        resourceRelationEvt.setCreateTime(nowTime);
        resourceRelationEvt.setUpdateTime(nowTime);
        resourceRelationEvt.setCreateUserName(username);
        resourceRelationEvt.setUpdateUserName(username);
        // 删除用户组与资源关系
        if(delResource !=null && delResource.size()>0) {
            resourceRelationEvt.setList(delResource);
            count = userGroupMapper.delGroupResource(resourceRelationEvt);
            logger.info("删除用户组与资源权限关系总数：" + count);
        }
        // 添加用户组与资源关系
        if(addResource != null && addResource.size()>0) {
            resourceRelationEvt.setList(addResource);
            count = userGroupMapper.addGroupResource(resourceRelationEvt);
            logger.info("增加用户组与资源权限关系总数：" + count);
        }
    }

    public Date nowDateTime() throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowDate = format.format(new Date());
        return format.parse(nowDate);
    }

}
